package com.hjt.gulimall.product.exception;

import com.hjt.common.exception.ErrorCodeEnum;
import com.hjt.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 统一异常处理
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.hjt.gulimall.product.controller"})
public class GulimallExceptionControllerAdvice {

    /**
     * 数据校验异常统一处理
     * @param exception
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handlerValidException(MethodArgumentNotValidException exception) {
        // getAllErrors() 获取所有的校验错误
        List<FieldError> errors = exception.getBindingResult().getFieldErrors();
        Map<String,String > map = new HashMap<>();
        errors.forEach(objectError -> {
            map.put(objectError.getField(), objectError.getDefaultMessage());
        });
        return R.error(ErrorCodeEnum.VALID_EXCEPTION.getCode(), ErrorCodeEnum.VALID_EXCEPTION.getMessage())
                .put("data", map);
    }

    // 处理未知异常
    @ExceptionHandler(Exception.class)
    public R handleException(Exception exception) {
        log.error("错误", exception);
        return R.error(ErrorCodeEnum.UNKNOWN_EXCEPTION.getCode(), ErrorCodeEnum.UNKNOWN_EXCEPTION.getMessage());
    }
}
